Operation details of Python timing [time datetime]

  • 2020-06-01 10:16:35
  • OfStack

This article illustrates an example of Python timing. I will share it with you for your reference as follows:

Contents:

1. The timestamp
2. Current time
3. The time difference
4. Time and date formatting symbols in python
Example 5.

1. The timestamp

The timestamp is the total number of seconds from January 1, 1970 (08:00:00 GMT) to the current time. Also known as the Unix timestamp (Unix Timestamp), it can be found anywhere in the unix, c world; A common form is a floating point number with milliseconds behind the decimal point. The subtraction of two timestamps is the time interval (in seconds).

Ex. :


import time
time1 = time.time()
time.sleep(15)
time2 = time.time()
print time2 - time1

Where, time.sleep () is the sleep function in seconds.

2. Current time


>>> import datetime,time
>>> now = time.strftime("%Y-%m-%d %H:%M:%S")
>>> print now
2016-04-30 17:02:26
>>> now = datetime.datetime.now()
>>> print now

3. The time difference

From 00:00 yesterday to 23:59 yesterday


>>> import datetime
>>> yestoday = datetime.datetime.now() - datetime.timedelta(days=1)
>>> t1 = "%s-00-00-00" % yestoday.strftime("%Y-%m-%d")
>>> t2 = "%s-23-59-59" % yestoday.strftime("%Y-%m-%d")
>>> print 't1', t1
t1 2016-04-29-00-00-00
>>> print 't2', t2
t2 2016-04-29-23-59-59

#2 now 10 hours back


>>> d1 = datetime.datetime.now()
>>> d3 = d1 + datetime.timedelta(hours=10)
>>> d3.ctime()
'Sun May 1 03:09:58 2

The number of seconds and the subtleties of #3 so 1 (note that the seconds and the subtleties are not equivalent transformations)


>>> import datetime
>>> starttime = datetime.datetime.now()
>>> endtime = datetime.datetime.now()
>>> starttime = datetime.datetime.now()
>>> endtime = datetime.datetime.now()
>>> print endtime - starttime
0:00:07.390988
>>> print (endtime - starttime).seconds
7
>>> print (endtime - starttime).microseconds
390988

The timestamp of the file


>>> import os
>>> statinfo=os.stat(r"C:/1.txt")
>>> statinfo
(33206, 0L, 0, 0, 0, 0, 29L, 1201865413, 1201867904, 1201865413)

Note: the last three items in the return value statinfo using os.stat are st_atime (access time), st_mtime (modification time), st_ctime (creation time), for example, get file modification time:


>>> statinfo.st_mtime
1201865413.8952832

Note: this time is an linux timestamp, which can be converted into an easy-to-understand format:


>>> import time
>>> time.localtime(statinfo.st_ctime)
(2008, 2, 1, 19, 30, 13, 4, 32, 0)

Note: 19:30 13 seconds on 1 February 2008 (2008-2-1 19:30:13)

4. Time and date formatting symbols in python

%y two-digit years are (00-99)
%Y 4-digit years (000-9999)
%m month (01-12)
%d 1 day within a month (0-31)
%H 24-hour system (0-23)
%I 12-hour system (01-12)
%M minutes (00=59)
%S seconds (00-59)
Simplify week names locally
Local full week name
%b local simplified month name
%B local full month name
%c local corresponding date and time representations
%j 1 day of the year (001-366)
The equivalent of %p local A.M. Or P.M
The number of weeks (00-53) in a year begins on Sunday
Week (0-6) begins on Sunday
Week 1 is the beginning of the week
%x local corresponding date representation
%X local corresponding time representation
%Z the name of the current time zone
The %% % sign itself

Example 5.


#! coding:utf-8
'''''  Date related operations  '''
from datetime import datetime
from datetime import timedelta
import calendar
DATE_FMT = '%Y-%m-%d'
DATETIME_FMT = '%Y-%m-%d %H:%M:%S'
DATE_US_FMT = '%d/%m/%Y'
'''''
 Formats several parameters that are commonly used 
Y  :  1999
y  : 99
m : mouth 02 12
M : minute 00-59
S : second
d : day
H : hour
'''
def dateToStr(date):
  ''''' the datetime Type the time to format your own desired format '''
  return datetime.strftime(date, DATETIME_FMT)
def strToDate(strdate):
  ''''' the str Become a date to do 1 Some operation '''
  return datetime.strptime(strdate, DATETIME_FMT)
def timeElement():
  ''''' To obtain 1 Each element of a time object '''
  now = datetime.today()
  print 'year: %s month: %s day: %s' %(now.year, now.month, now.day)
  print 'hour: %s minute: %s second: %s' %(now.hour, now.minute, now.second)
  print 'weekday: %s ' %(now.weekday()+1) #1 Weeks from 0 The start of the 
def timeAdd():
  '''''
   Time plus or minus, before 1 Days later 1 Day operations such as 
  datetime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])
   The parameter can be positive or negative 
   The resulting object can be added or subtracted   Times the number and the absolute value 
  '''
  atime = timedelta(days=-1)
  now = datetime.strptime('2001-01-30 11:01:02', DATETIME_FMT)
  print now + atime
  print now - abs(atime)
  print now - abs(atime)*31
def lastFirday():
   today = datetime.today()
   targetDay = calendar.FRIDAY
   thisDay = today.weekday()
   de = (thisDay - targetDay) % 7
   res = today - timedelta(days=de)
   print res
def test():
  print dateToStr(datetime.today())
  print strToDate('2013-01-31 12:00:01')
  timeElement()
  timeAdd()
  lastFirday()
if __name__=='__main__':
  test()

The results of


Connected to pydev debugger (build 141.1899)
2016-05-18 10:40:26
2013-01-31 12:00:01
year: 2016 month: 5 day: 18
hour: 10 minute: 41 second: 13
weekday: 3
2001-01-29 11:01:02
2001-01-29 11:01:02
2000-12-30 11:01:02
2016-05-13 10:41:37.001000

PS: this site also provides several online tools about Unix timestamp conversion and date conversion, which are very practical and useful for your reference:

Unix timestamp (timestamp) conversion tool:
http://tools.ofstack.com/code/unixtime

Online date/days calculator:
http://tools.ofstack.com/jisuanqi/date_jisuanqi

Online calendar:
http://tools.ofstack.com/bianmin/wannianli

Online lunar/solar calendar conversion tool:
http://tools.ofstack.com/bianmin/yinli2yangli

More about Python related topics: interested readers to view this site "Python date and time operating skills summary", "Python data structure and algorithm tutorial", "Python Socket programming skills summary", "Python function using techniques", "Python string skills summary", "Python introduction and advanced tutorial" and "Python file and directory skills summary"

I hope this article has been helpful to you in Python programming.


Related articles: